package com.howard.webapp.familymanagement.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.howard.webapp.familymanagement.domain.Menu;
import com.howard.webapp.familymanagement.repository.BaseRepository;
import com.howard.webapp.familymanagement.repository.MenuRepository;
import com.howard.webapp.familymanagement.service.MenuService;

@Service
public class MenuServiceImpl implements MenuService{
	@Autowired
	private MenuRepository repository;
	
	public BaseRepository<Menu,Long> getRepository() {
		return repository;
	}


	public List<Menu> findAllMenu() {
		
		List<Menu> dbMenuList = repository.findAll();
		List<Menu> uiMenuList = new ArrayList<Menu>();
		
		//add root menu
		for(Menu menu : dbMenuList){
			if(menu.getUrl() != null){
				menu.addAttribute("url", menu.getUrl());
			}
			buildAllMenu(menu, dbMenuList, uiMenuList);
		}
		return uiMenuList;
//		return repository.findAll();
	}
	
	private void buildAllMenu(Menu menu, List<Menu> dbMenuList, List<Menu> uiMenuList){
		if(menu.getpId() == null){
			uiMenuList.add(menu);
		}
		else{
			Menu parentMenu = getParentMenu(menu, dbMenuList);
			parentMenu.addChild(menu);
		}
	}
	
	private Menu getParentMenu(Menu menu, List<Menu> dbMenuList){
		for(Menu parentMenu : dbMenuList){
			if(menu.getpId().compareTo(parentMenu.getId()) == 0){
				return parentMenu;
			}
		}
		return null;
	}

	

}